/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vienthonga.register.action;

import com.vienthonga.hibernate.pojo.TUser;
import com.vienthonga.register.logic.RegisterLogic;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author DoanHa
 */
public class RegisterAction extends Action {

    private static final Logger logger = Logger.getLogger(
            RegisterAction.class.getName());
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.log(Level.INFO, mapping.getPath());

        RegisterForm registerForm = (RegisterForm) form;
        RegisterLogic logic = new RegisterLogic();

        ActionErrors errors = new ActionErrors();
        //kiem tra password
        if (!registerForm.getPassword().equals(registerForm.getRetypePassword())) {
            errors.add("ErrorRetypePassword", new ActionMessage("error.retypePassword"));
        }

        //kiem tra email nay ton tai chua
        boolean isCheckExistEmail = logic.CheckExistEmail(registerForm.getEmail());
        if (isCheckExistEmail == true) {
            errors.add("ExistEmail", new ActionMessage("errors.email.exist"));
        }

        //kiem tra captcha
        boolean captchaResult = logic.CheckCaptcha(request, registerForm.getCaptcha());
        if (captchaResult == false) {
            errors.add("errorCaptcha", new ActionMessage("error.captcha"));
        } else {
            TUser user = new TUser();
            user.setUFullname(registerForm.getFullName());
            user.setUEmail(registerForm.getEmail());
            user.setUPassword(registerForm.getPassword());

            boolean result = logic.Register(user);
            if (result == false) {
                errors.add("UnsuccessfulRegister", new ActionMessage("error.UnsuccessfulRegister"));
            }
        }


        if (errors.isEmpty()) {
            return mapping.findForward(SUCCESS);
        } else {
            addErrors(request, errors);
            return mapping.findForward(FAILURE);
        }
    }
}
